﻿@using System.Collections.Concurrent
@inject IStringLocalizer<ValidateForms> Localizer

<ValidateForm @ref="ComplexForm" Model="@ComplexModel" OnInvalidSubmit="@OnInvalidComplexModel"
              OnValidSubmit="@OnValidComplexModel">
    <div class="row g-3">
        <div class="col-12 col-sm-6">
            <BootstrapInput @bind-Value="@ComplexModel.Name" />
        </div>
        <div class="col-12 col-sm-6">
            <BootstrapInput @bind-Value="@ComplexModel.Dummy.Dummy2.Name" />
        </div>
        <div class="col-12">
            <Button ButtonType="@ButtonType.Submit" Text="@Localizer["ValidateFormsSubmitButtonText"]" />
        </div>
    </div>
</ValidateForm>
<ConsoleLogger @ref="Logger" class="mt-3" />
<p class=mt-3>
    @foreach (var key in GetValueChagnedFieldCollection())
    {
        <div>
            <span>@key.Key.Model.GetType().Name</span>.<span>@key.Key.FieldName</span>: <span>@key.Value</span>
        </div>
    }
</p>

@code {
    [NotNull]
    private ConsoleLogger? Logger { get; set; }

    [NotNull]
    private ValidateForm? ComplexForm { get; set; }

    [NotNull]
    private ComplexFoo? ComplexModel { get; set; }

    private ConcurrentDictionary<FieldIdentifier, object?> GetValueChagnedFieldCollection() => ComplexForm?.ValueChagnedFields ?? new ConcurrentDictionary<FieldIdentifier, object?>();

    private class ComplexFoo : Foo
    {
        [NotNull]
        public Dummy1? Dummy { get; set; }
    }

    private class Dummy1
    {
        [NotNull]
        public Dummy2? Dummy2 { get; set; }
    }

    private class Dummy2
    {
        [Required]
        public string? Name { get; set; }
    }

    private Task OnInvalidComplexModel(EditContext context)
    {
        Logger.Log(Localizer["OnInvalidSubmitCallBackLog"]);
        return Task.CompletedTask;
    }

    private Task OnValidComplexModel(EditContext context)
    {
        Logger.Log(Localizer["OnValidSubmitCallBackLog"]);
        ComplexForm.SetError("Dummy.Dummy2.Name", Localizer["DatabaseExistLog"]);
        return Task.CompletedTask;
    }

    /// <summary>
    /// OnInitializedAsync 方法
    /// </summary>
    /// <returns></returns>
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        // 切换线程 模拟异步通过 webapi 加载数据
        await Task.Yield();

        ComplexModel = new ComplexFoo()
        {
            Dummy = new Dummy1() { Dummy2 = new Dummy2() },
        };
    }
}

